package com.dj.dormitory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dj.dormitory.entity.Menu;
import com.dj.dormitory.mapper.MenuMapper;
import com.dj.dormitory.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DJ同学
 * @since 2021-01-24
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {


    //获得树形结构目录
    @Override
    public List<Menu> getTree(Integer type) {
        //查询出符合条件的菜单对应type
        List<Menu> all = this.baseMapper.getMenuByType(type);
        //进行封装成树形结构
        List<Menu> tree = all.stream()
                //得到所有一级分类
                .filter(entity-> entity.getParentId()==0)
                //查找子菜单
                .map((menu)->{
                    menu.setChild(getChild(menu.getId(),all));
                    return menu;
                })
                .sorted((item1,item2)->{
                    return (item1.getId()==null?0:item1.getId()) - (item2.getId()==null?0:item2.getId());
                }).collect(Collectors.toList());
        if(tree.size()==0){
            tree = null;
        }
        return tree;
    }

    @Override
    public List<Menu> getMenuByType(int i) {
        return this.baseMapper.getMenuByType(i);
    }


    private List<Menu> getChild(Integer id,List<Menu> all){
        List<Menu> child =
            all.stream()
                .filter(item->id==item.getParentId())
                .map((menu)->{
                    menu.setChild(getChild(menu.getId(),all));
                    return menu;
                })
                .sorted((item1,item2)->{
                    return (item1.getId()==null?0:item1.getId()) - (item2.getId()==null?0:item2.getId());
                }).collect(Collectors.toList());
        if(child.size()==0){
            child = null;
        }
        return child;
    }
}
